// router.js
import Vue from 'vue'
import {
	RouterMount,
	createRouter,
	runtimeQuit
} from 'uni-simple-router';
import store from '@/store/index.js'


const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,
	routes: [...ROUTES, {
		path: '*',
		redirect: (to) => {
			return {
				name: 'home'
			}
		}
	}],
	routerErrorEach: ({
		type,
		level,
		...args
	}) => {
		// #ifdef APP-PLUS
		if (type === 3) {
			router.$lockStatus = false
			const pages = getCurrentPages()
			const currentPage = pages[pages.length - 1]
			if (level == 1 && args.uniActualData.from === 'backbutton') {
				if (currentPage.$page.meta.isQuit) {
					runtimeQuit()
				}
			}
		}
		// #endif
	},
});


//全局路由前置守卫
router.beforeEach(async (to, from, next) => {
	const token = store.getters.token
	if (to.query.pid) {
		uni.setStorage({
			key: 'pid',
			data: to.query.pid
		})
	}

	if (token) {
		if (to.path == '/pages/login/index') {
			next({
				path: '/pages/index/index',
				NAVTYPE: 'pushTab'
			})
		} else {
			next()
		}
	} else {
		if (store.getters.whitePageList.indexOf(to.path) !== -1) {
			next()
		} else {

			// Vue.prototype.$util.msg('用户未登录，无法访问页面！')
			console.log('用户未登录，无法访问页面！')
			next({
				path: `/pages/login/index`,
				query: {
					redirect: Vue.prototype.$util.getRedirectUrl(to.path, to.query)
				},
				NAVTYPE: 'push'
			})
		}
	}
})
// 全局路由后置守卫
router.afterEach((to, from) => {
	console.log(`from:${from.path},to:${to.path}.跳转结束`)
})

export {
	router,
	RouterMount
}